package com.example.p001_interview02;

import cn.hutool.core.date.DateUtil;

import java.util.LinkedList;

/**
 * 写一个固定容量同步容器，拥有put和get方法，以及getCount方法，能够支持2个生产者线程以及10个消费者线程的阻塞调用
 * @param <T>
 */
public class Container02<T> {

    private final int MAX = 20;
    private LinkedList<T> c = new LinkedList<>();

    public synchronized void put(T t) {

        while (c.size() == MAX) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        c.add(t);
        this.notifyAll();

        System.out.println(DateUtil.now() +" "+ Thread.currentThread().getName() + " notify get's wait~~~~~~~~");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized T get() {

        while (c.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        T t = c.removeFirst();
        this.notifyAll();

        return t;
    }

    public synchronized int getCount() {
        return c.size();
    }

    public static void main(String[] args) {
        Container02 c = new Container02();

        // 10个消费者
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                System.out.println(DateUtil.now() +" "+ Thread.currentThread().getName() + " 开始消费");
                for (int j = 0; j < 4; j++) {
                    Object o = c.get();
                    System.out.println(DateUtil.now() +" "+ Thread.currentThread().getName() + " 获得：" + o);
                }
            }, "consumer" + i).start();
        }

        // 2个生产者
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                System.out.println(DateUtil.now() +" "+ Thread.currentThread().getName() + " 开始生产");
                for (int j = 0; j < 20; j++) {
                    c.put(Thread.currentThread().getName() +  "-" + j);
                }
                System.out.println(DateUtil.now() +" "+ Thread.currentThread().getName() + " 结束生产");

            }, "producter" + i).start();
        }

    }

}
